package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.CommentDTO;
import com.example.dto.CommentLikeDTO;
import com.example.dto.CommentQueryDTO;
import com.example.entity.Comment;
import com.example.entity.User;
import com.example.handlers.BaseContext;
import com.example.mapper.CommentMapper;
import com.example.mapper.ArticleMapper;
import com.example.service.CommentService;
import com.example.service.UserService;
import com.example.vo.CommentVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 博客评论表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2024-10-20
 */
@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private UserService userService;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public Long addComment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        BeanUtil.copyProperties(commentDTO, comment);
        
        // 获取当前登录用户ID
        Integer currentUserId = BaseContext.getCurrentId();
        if (currentUserId != null) {
            // 已登录用户
            comment.setUserId(currentUserId.longValue());
            
            // 获取用户信息
            User user = userService.getById(currentUserId);
            if (user != null) {
                comment.setNickname(user.getNickname());
                comment.setAvatar(user.getAvatar());
            } else {
                // 如果获取不到用户信息，设置默认昵称
                comment.setNickname("用户" + currentUserId);
                comment.setAvatar("https://via.placeholder.com/150?text=用户");
            }
        } else {
            // 前端移除了昵称输入，但数据库字段不能为空，给一个默认值
            comment.setNickname("匿名用户");
            comment.setAvatar("https://via.placeholder.com/150?text=匿名");
        }
        
        // 不再获取IP地址，将 ipAddress 字段设置为空
        comment.setIpAddress(null);
        
        // 设置初始状态和时间
        comment.setStatus(1); // 设置为正常状态
        comment.setLikeCount(0);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUpdatedTime(LocalDateTime.now());
        
        // 保存到数据库
        this.save(comment);
        
        return comment.getId();
    }

    @Override
    public IPage<CommentVO> getCommentsByArticleId(CommentQueryDTO queryDTO) {
        // 1. 查询所有评论
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getArticleId, queryDTO.getArticleId());
        // 不再按状态过滤，因为已删除的记录已经物理删除
        wrapper.orderByDesc(Comment::getCreatedTime); // 按时间倒序排序
        
        // 创建分页对象
        Page<Comment> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<Comment> commentPage = this.page(page, wrapper);
        
        // 2. 转换为VO
        List<CommentVO> commentVOList = new ArrayList<>();
        Map<Long, CommentVO> commentMap = new HashMap<>();
        
        // 先将所有评论转换为VO并存入Map
        for (Comment comment : commentPage.getRecords()) {
            CommentVO commentVO = new CommentVO();
//            BeanUtil.copyProperties(comment, commentVO);

            commentVO.setId(comment.getId());
            commentVO.setArticleId(comment.getArticleId());
            commentVO.setContent(comment.getNickname());
            commentVO.setAvatar(comment.getAvatar());
            commentVO.setContent(comment.getContent());
            commentVO.setParentId(comment.getParentId());
            commentVO.setCreatedTime(comment.getCreatedTime());
            commentVO.setLikeCount(comment.getLikeCount());
            commentVO.setChildren(new ArrayList<>());
//            commentVO.setChildren(new ArrayList<>());

            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(User::getAdminId, comment.getUserId());
            User user = userService.getOne(userWrapper);

            commentVO.setAvatar(user.getAvatar());
            commentVO.setNickname(user.getNickname());

            
            // 放入Map中，方便后续设置父子关系
            commentMap.put(comment.getId(), commentVO);
            
            // 如果是顶级评论，添加到结果列表
            if (comment.getParentId() == null) {
                commentVOList.add(commentVO);
            }
        }
        
        // 设置父子关系
        for (Comment comment : commentPage.getRecords()) {
            if (comment.getParentId() != null && commentMap.containsKey(comment.getParentId())) {
                CommentVO parentVO = commentMap.get(comment.getParentId());
                CommentVO childVO = commentMap.get(comment.getId());
                parentVO.getChildren().add(childVO);
            }
        }
        
        // 3. 构建分页结果对象
        IPage<CommentVO> resultPage = new Page<>(commentPage.getCurrent(), commentPage.getSize(), commentPage.getTotal());
        resultPage.setRecords(commentVOList);
        
        return resultPage;
    }

    @Override
    public boolean likeComment(CommentLikeDTO likeDTO) {
        Comment comment = this.getById(likeDTO.getCommentId());
        if (comment == null) {
            return false;
        }
        
        // 增加点赞数
        comment.setLikeCount(comment.getLikeCount() + 1);
        comment.setUpdatedTime(LocalDateTime.now());
        
        return this.updateById(comment);
    }

    @Override
    public IPage<CommentVO> getUserComments(Long userId, int pageNum, int pageSize, boolean isAdmin) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        
        // 如果不是管理员，则只查询自己的评论
        if (!isAdmin) {
            wrapper.eq(Comment::getUserId, userId);
        }
        
        // 按时间倒序排序
        wrapper.orderByDesc(Comment::getCreatedTime);
        
        // 创建分页对象
        Page<Comment> page = new Page<>(pageNum, pageSize);
        Page<Comment> commentPage = this.page(page, wrapper);
        
        // 转换为VO
        List<CommentVO> commentVOList = new ArrayList<>();
        for (Comment comment : commentPage.getRecords()) {
            CommentVO commentVO = new CommentVO();
//            BeanUtil.copyProperties(comment, commentVO);
            commentVO.setId(comment.getId());
            commentVO.setArticleId(comment.getArticleId());
            commentVO.setContent(comment.getNickname());
            commentVO.setAvatar(comment.getAvatar());
            commentVO.setContent(comment.getContent());
            commentVO.setParentId(comment.getParentId());
            commentVO.setCreatedTime(comment.getCreatedTime());
            commentVO.setLikeCount(comment.getLikeCount());
            commentVO.setChildren(new ArrayList<>());

            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(User::getAdminId, comment.getUserId());
            User user = userService.getOne(userWrapper);

            commentVO.setAvatar(user.getAvatar());
            commentVO.setNickname(user.getNickname());

            commentVOList.add(commentVO);
        }
        
        // 构建分页结果对象
        IPage<CommentVO> resultPage = new Page<>(commentPage.getCurrent(), commentPage.getSize(), commentPage.getTotal());
        resultPage.setRecords(commentVOList);
        
        return resultPage;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Long commentId, Long userId, boolean isAdmin) {
        Comment comment = this.getById(commentId);
        if (comment == null) {
            return false;
        }
        
        // 检查权限：只有评论作者或管理员才能删除评论
        if (!isAdmin && !comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除此评论");
        }
        
        // 物理删除评论记录
        boolean result = this.removeById(commentId);
        
        return result;
    }

    @Override
    public Integer getCommentCounts() {
        // 获取当前登录用户ID
        Integer id = BaseContext.getCurrentId();
        if (id == null) {
            return 0;
        }
        // 使用MybatisPlus内置方法统计当前用户评论数
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getUserId, id.longValue());
        return Math.toIntExact(this.count(wrapper));
    }
    
    @Override
    public Integer getUserCommentCounts(Long userId) {
        if (userId == null) {
            return 0;
        }
        // 使用MybatisPlus内置方法统计指定用户评论数
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getUserId, userId);
        return Math.toIntExact(this.count(wrapper));
    }
} 